/**
 * Created by tanbingqin on 2019/4/10.
 */
import React from 'react';
import { connect } from 'react-redux';
import { Modal, message, Button, Input, Row, Col, Checkbox, Tree, Switch, Spin, Icon, Collapse, Radio } from 'antd'
import { messages } from 'share/common'
import errorMessage from 'share/errorMessage'
import debounce from 'lodash.debounce';
import 'styles/setting/workflow/comp/select-form.scss'
import selectFormService from 'containers/setting/new-workflow/list-comp/copy-comp/select-form.service'
const Search = Input.Search;
const { TreeNode } = Tree;
const Panel = Collapse.Panel;
const RadioGroup = Radio.Group;

class SelectForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      keyword: '', //搜索的关键字
      searchLoading: false, //搜索的loading
      visibleSelectForm: false,
      disabled: false, //防止重复复制
      selectFormScopeTenant: [], //集团模式下可选表单范围
      selectFormScope: [], //公司模式下可选表单范围
      selectedFormList: [], //公司模式下已选表单
      selectedFormListTenant: [], //集团模式下已选表单
      copyFormDeploy: true, //是否复制表单配置 默认为是
      copyConditionMode: 1, //条件复制匹配模式，只有版本号第一位大于0的可以配该模式
    };
    this.handleSearchStep2 = debounce(this.handleSearchStep2, 500);
  }

  showSelectForm = () => {
    this.setState({
      keyword: '',
      visibleSelectForm: true,
      disabled: false,
      selectFormScopeTenant: [],
      selectFormScope: [],
      selectedFormList: [],
      selectedFormListTenant: []
    }, () => {
      this.getFormData();
    });
  };

  getFormData = (keyword) => {
    const { tenantMode, setOfBooksId } = this.props;
    let params = {
      searchName: keyword,
      setOfBooksId: tenantMode ? setOfBooksId : undefined
    };
    this.setState({searchLoading: true});
    selectFormService.getFormList(params).then(res => {
      this.setState({searchLoading: false});
      if (res.data && res.data.length) {
        if (tenantMode) {
          let selectFormScopeTenant = [];
          res.data.map(item => {
            let formBlock = {};
            formBlock.label = item.fromType === 1 ? item.companyName : item.setOfBooksName;
            formBlock.id = item.fromType === 1 ? item.companyId : item.setOfBooksId;
            formBlock.formScope = this.handleFormList(item.formList);
            selectFormScopeTenant.push(formBlock);
          });
          this.setState({selectFormScopeTenant});
        } else {
          this.setState({selectFormScope: this.handleFormList(res.data[0].formList)});
        }
      } else {
        //搜索结果为空
        if (tenantMode) {
          this.setState({selectFormScopeTenant: []});
        } else {
          this.setState({selectFormScope: []});
        }
      }
    }).catch(e => {
      this.setState({searchLoading: false});
      errorMessage(e.response);
    });
  };

  //把表单按类型分类后返回
  handleFormList = (formList) => {
    let tempSelectFormScope = [
      {label: messages('setting.key20')/*申请单*/, entityType: 1001, key: 1001, selectable: false, type: 'label', formList: []},
      {label: messages('setting.key847')/*报销单*/, entityType: 1002, key: 1002, selectable: false, type: 'label', formList: []},
      {label: messages('setting.key1742')/*借款单*/, entityType: 3001, key: 3001, selectable: false, type: 'label', formList: []},
      {label: messages('setting.key1173')/*其他*/, entityType: 4001, key: 4001, selectable: false, type: 'label', formList: []}
    ];
    formList.map(form => {
      let index = 0;
      switch(form.entityType){
        case 1001:
          index = 0;
          break;
        case 1002:
          index = 1;
          break;
        case 3001:
          index = 2;
          break;
        case 4001:
          index = 3;
          break;
      }
      tempSelectFormScope[index].formList.push({
        label: form.formName,
        key: form.formOID,
        selectable: true
      });
    });
    let selectFormScope = [];
    tempSelectFormScope.map(scope => {
      if (scope.formList.length) {
        selectFormScope.push(scope);
      }
    });
    selectFormScope.expandedKeys = ['1001', '1002', '3001', '4001'];//默认全部展开
    return selectFormScope;
  };

  handleSearch = (value) => {
    this.setState({keyword: value});
    this.handleSearchStep2(value);
  };

  handleSearchStep2 = (value) => {
    this.getFormData(value);
  };

  handleCancel = () => {
    this.setState({visibleSelectForm: false});
  };

  showConfirm = () => {
    const { selectedFormList, selectedFormListTenant, disabled } = this.state;
    if (disabled) {
      return;
    }
    if (!selectedFormList.length && !selectedFormListTenant.length) {
      message.error(messages('setting.key1907')/*请至少选择一个表单*/);
      return;
    }
    Modal.confirm({
      title: messages('setting.key1908')/*注意*/,
      content: messages('setting.key1909')/*复制审批流时，会丢失部分目标表单无法配置的审批人或配置。*/,
      onOk: () => this.handleOk()
    });
  };

  handleOk = () => {
    const { tenantMode, version, formOID, company, setOfBooksId } = this.props;
    const { selectedFormList, selectedFormListTenant, copyFormDeploy, copyConditionMode } = this.state;
    let booksID = tenantMode ? setOfBooksId : company.setOfBooksId;
    let params = {
      copyFormDeploy,
      sourceForm: {
        formOID,
        version,
        booksID
      },
      targetForm: []
    };
    if (this.isShowModeCopy()) {
      params.copyConditionMode = copyConditionMode;
    }
    if (tenantMode) {
      selectedFormListTenant.map(block => {
        block.selectedFormList.map(item => {
          params.targetForm.push({
            booksID,
            formOID: item.formOID
          });
        });
      });
    } else {
      selectedFormList.map(item => {
        params.targetForm.push({
          booksID,
          formOID: item.formOID
        });
      });
    }
    this.setState({disabled: true});
    selectFormService.copyWorkFlow(params).then(res => {
      this.setState({visibleSelectForm: false});
      this.props.copySuccess();
    }).catch(e => {
      this.setState({visibleSelectForm: false});
      errorMessage(e.response);
    });
  };

  //处理选中表单
  handleSelectForm = (selectedKeys, info, formBlock) => {
    const { tenantMode } = this.props;
    let { selectedFormList, selectedFormListTenant } = this.state;
    let operateItem = {
      formOID: info.node.props.dataRef.key,
      formName: info.node.props.dataRef.label
    };
    if (tenantMode) {
      if (info.selected) {
        let blockIndex = -1;
        selectedFormListTenant.map((block, index) => {
          if (block.id === formBlock.id) {
            blockIndex = index;
          }
        });
        if (blockIndex > -1) {
          selectedFormListTenant[blockIndex].selectedFormList.push(operateItem);
        } else {
          selectedFormListTenant.push({
            label: formBlock.label,
            id: formBlock.id,
            selectedFormList: [operateItem]
          });
        }
        this.setState({selectedFormListTenant});
      } else {
        this.handleDelete(operateItem);
      }
    } else {
      if (info.selected) {
        selectedFormList.push(operateItem);
        this.setState({selectedFormList});
      } else {
        this.handleDelete(operateItem);
      }
    }
  };

  //处理删除表单
  handleDelete = (form) => {
    const { tenantMode } = this.props;
    let { selectedFormList, selectedFormListTenant } = this.state;
    if (tenantMode) {
      let spliceBlockIndex = -1;
      let spliceFormIndex = -1;
      selectedFormListTenant.map((block, blockIndex) => {
        block.selectedFormList.map((item, formIndex) => {
          if (item.formOID === form.formOID) {
            spliceFormIndex = formIndex;
            spliceBlockIndex = blockIndex;
          }
        });
      });
      if (spliceBlockIndex > -1 && spliceFormIndex > -1) {
        selectedFormListTenant[spliceBlockIndex].selectedFormList.splice(spliceFormIndex, 1);
        if (!selectedFormListTenant[spliceBlockIndex].selectedFormList.length) {
          selectedFormListTenant.splice(spliceBlockIndex, 1);
        }
      }
      this.setState({selectedFormListTenant});
    } else {
      let spliceIndex = -1;
      selectedFormList.map((item, index) => {
        if (item.formOID === form.formOID) {
          spliceIndex = index;
        }
      });
      if (spliceIndex > -1) {
        selectedFormList.splice(spliceIndex, 1);
      }
      this.setState({selectedFormList});
    }
  };

  //渲染集团模式下可选表单范围
  renderSelectScopeTenant = () => {
    const { selectFormScopeTenant, selectedFormListTenant } = this.state;
    if (selectFormScopeTenant && selectFormScopeTenant.length) {
      return selectFormScopeTenant.map(item => {
        let selectedKeys = [];
        selectedFormListTenant.map(formBlock => {
          if (formBlock.id === item.id) {
            formBlock.selectedFormList.map(form => {
              selectedKeys.push(form.formOID);
            });
          }
        });
        return (
          <div key={item.id}>
            <span className="tenant-label">{item.label}</span>
            <Tree multiple
                  expandedKeys={item.formScope.expandedKeys}
                  onExpand={(expandedKeys) => this.handleExpand(expandedKeys, item.id)}
                  onSelect={(selectedKeys, e) => this.handleSelectForm(selectedKeys, e, item)}
                  selectedKeys={selectedKeys}>
              {this.renderTreeNodes(item.formScope)}
            </Tree>
          </div>
        )
      })
    } else {
      return (
        <div className="empty-block"> {messages('setting.key1910')/*未找到对应搜索结果*/}
        </div>
      )
    }
  };

  //渲染公司模式下可选表单范围
  renderSelectScope = () => {
    const { selectFormScope, selectedFormList } = this.state;
    let selectedKeys = [];
    selectedFormList.map(item => {
      selectedKeys.push(item.formOID);
    });
    if (selectFormScope && selectFormScope.length) {
      return (
        <Tree multiple
              expandedKeys={selectFormScope.expandedKeys}
              onExpand={this.handleExpand}
              onSelect={this.handleSelectForm}
              selectedKeys={selectedKeys}>
          {this.renderTreeNodes(selectFormScope)}
        </Tree>
      )
    } else {
      return (
        <div className="empty-block"> {messages('setting.key1910')/*未找到对应搜索结果*/}
        </div>
      )
    }
  };

  //处理展开 关闭
  /**
   *
   * @param expandedKeys 展开行的key
   * @param id 集团模式下处理展开的tree的id
   */
  handleExpand = (expandedKeys, id) => {
    const { tenantMode } = this.props;
    let { selectFormScope, selectFormScopeTenant } = this.state;
    if (tenantMode) {
      selectFormScopeTenant.map(item => {
        if (item.id === id) {
          item.formScope.expandedKeys = expandedKeys;
        }
      });
      this.setState({selectFormScopeTenant});
    } else {
      selectFormScope.expandedKeys = expandedKeys;
      this.setState({selectFormScope});
    }
  };

  //渲染表单节点
  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.formList && item.formList.length) {
        return (
          <TreeNode
            title={this.renderTreeNodesTitle(item)}
            key={item.key}
            selectable={item.selectable}
            dataRef={item}>
            {this.renderTreeNodes(item.formList)}
          </TreeNode>
        );
      } else {
        return (
          <TreeNode title={this.renderTreeNodesTitle(item)}
                    key={item.key}
                    selectable={item.selectable}
                    dataRef={item}/>
        );
      }
    });
  };

  //渲染树形节点的title
  renderTreeNodesTitle = (item) => {
    if (item.type === "label") {
      return (
        <div title={item.title}>
          <Icon type="folder"/> &nbsp;
          <span className='node-title'>
            {item.label}
          </span>
        </div>
      )
    } else {
      return (
        <div title={item.title}>
          <Icon type="file-text"/> &nbsp;
          <span className='node-title'>
            {item.label}
          </span>
        </div>
      )
    }
  };

  //渲染单个公司下已选表单
  renderSelectedForm = (selectedFormList) => {
    return (
      <div>
        {selectedFormList.map(form => {
          return (
            <Row type="flex" align="middle" className="selected-row">
              <Col span={20}>
                <Icon type="file-text" />
                {form.formName}
              </Col>
              <Col span={4} style={{textAlign: 'right'}}>
                <Icon type="close" style={{cursor: 'pointer'}} onClick={() => this.handleDelete(form)} />
              </Col>
            </Row>
          )
        })}
      </div>
    )
  };

  //渲染集团模式下已选表单
  renderSelectedFormTenant = () => {
    const { selectedFormListTenant } = this.state;
    return (
      <div>
        {selectedFormListTenant.map(item => {
          return (
            <div key={item.id}>
              <span className="tenant-label">{item.label}</span>
              {this.renderSelectedForm(item.selectedFormList)}
            </div>
          )
        })}
      </div>
    )
  };

  handleChangeCheckbox = (value, key) => {
    this.setState({[key]: value});
  };

  //是否展示条件复制匹配模式的配置，只有新表单有
  isShowModeCopy = () => {
    const { version } = this.props;
    let isShow = false;
    if (version && Number(version.split('.')[0]) > 0) {
      isShow = true;
    }
    return isShow;
  };

  render() {
    const { text, tenantMode } = this.props;
    const { visibleSelectForm, selectedFormList, searchLoading, keyword, disabled, copyFormDeploy, copyConditionMode } = this.state;
    return (
      <div style={{display: 'inline'}}>
        <span onClick={this.showSelectForm}>{text}</span>
        <Modal className="select-form-workflow"
               title={messages('setting.key1911')/*复制审批流至*/}
               visible={visibleSelectForm}
               onCancel={this.handleCancel}
               width={"900px"}
               footer={[
                 <Button key="back" onClick={this.handleCancel}>{messages('common.cancel')/*取消*/}</Button>,
                 <Button key="submit" type="primary" loading={disabled} onClick={this.showConfirm}>{messages('common.ok')/*确定*/}</Button>
               ]}>
          <Collapse bordered={false} style={{marginTop: '-20px', marginBottom: '10px'}}>
            <Panel header={messages('setting.key2006')/*选项*/} key="option">
              <Checkbox checked={copyFormDeploy} onChange={e => this.handleChangeCheckbox(e.target.checked, 'copyFormDeploy')}>{messages('setting.key2026')/*复制时包含表单配置*/}</Checkbox>
              {this.isShowModeCopy() && (
                <div style={{marginTop: '15px'}}> {messages('setting.key2007')/*条件复制匹配模式：*/}
                  <RadioGroup value={copyConditionMode} onChange={e => this.handleChangeCheckbox(e.target.value, 'copyConditionMode')}>
                    <Radio value={1}>{messages('setting.key2008')/*控件类别+名称*/}</Radio>
                    <Radio style={{marginLeft: 30}} value={2}>{messages('setting.key2009')/*控件类别+编码*/}</Radio>
                  </RadioGroup>
                </div>
              )}
            </Panel>
          </Collapse>
          <Row gutter={10} style={{lineHeight: '30px', marginBottom: 10}}>
            <Col span={12}>
              <Row>
                <Col span={8}>{messages('setting.key1912')/*可选表单*/}</Col>
                <Col span={16} style={{textAlign: 'right'}}>
                  <Search style={{width: 200}}
                          placeholder={messages('setting.key1913')/*表单名称/编码*/}
                          value={keyword}
                          onChange={(e) => this.handleSearch(e.target.value)} />
                </Col>
              </Row>
            </Col>
            <Col span={12}> {messages('setting.key1914')/*已选表单*/}
            </Col>
          </Row>
          <Row gutter={10}>
            <Col span={12}>
              <Spin spinning={searchLoading}>
                <div className="operate-block">
                  {tenantMode ? this.renderSelectScopeTenant() : this.renderSelectScope()}
                </div>
              </Spin>
            </Col>
            <Col span={12}>
              <div className="operate-block">
                {tenantMode ? this.renderSelectedFormTenant() : this.renderSelectedForm(selectedFormList)}
              </div>
            </Col>
          </Row>
        </Modal>
      </div>
    )
  }
}

SelectForm.PropTypes = {
  text: React.PropTypes.string,
  copySuccess: React.PropTypes.func,
  setOfBooksId: React.PropTypes.string,
  formOID: React.PropTypes.string,
  version: React.PropTypes.string
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    user: state.login.user,
    language: state.main.language
  }
}

export default connect(mapStateToProps)(SelectForm);
